home *** CD-ROM | disk | FTP | other *** search
/ PC Active 2009 July/August / PC Active NR.227.iso / Software / Games / windows / Freeciv-2.1.9-win32-gtk2-setup.exe / doc / HACKING < prev    next >
Encoding:
Text File  |  2009-03-25  |  46.7 KB  |  1,063 lines

  1.                           Freeciv Hacker's Guide
  2.               
  3. This guide is intended to be a help for developers, wanting to mess with
  4. Freeciv program. 
  5.  
  6. Here and there, you'll see some comments marked as [...], containing more
  7. personal thoughts on the design, why it looks like it does, and sometimes what 
  8. went wrong. I hope developers will find that interesting too.
  9.  
  10. To read about the AI, see README.AI
  11.  
  12. ===========================================================================
  13. Basic
  14. ===========================================================================
  15. Freeciv is a client/server civilization style of game.
  16. The client is pretty dumb. Almost all calculations are performed on the
  17. server.
  18.  
  19. [It wasn't like this always. Originally more code was placed in the
  20. common/ dir, allowing the client to do some of the world updates itself. 
  21. The end_of_turn city-refresh was for example performed both on the server 
  22. and on the client. However things got quite complex, more and more info
  23. was needed on the client-side(security problem). Little by little we moved 
  24. more code to the server, and as of 1.5 the client is quite dumb -PU]
  25.  
  26. The source code has the following important directories:
  27. common: data structures and code used by both the client and server.
  28. server: (duh)
  29. client: common client code
  30. client/* (fx gui-gtk): a specific gui implementation of the client.
  31. data: graphics, rulesets and stuff
  32. po: translations
  33. ai: the ai, later linked into the server.
  34.  
  35. Freeciv is written in C.  Header files should be compatible with C++ so
  36. that C++ add-ons (particularly new clients) are possible.  See the
  37. CodingStyle file for more.
  38.  
  39. ===========================================================================
  40. Server
  41. ===========================================================================
  42. General:
  43.  
  44. The server main loop basically looks like:
  45.  
  46.   while(server_state==RUN_GAME_STATE) { /* looped once per turn */
  47.     do_ai_stuff();   /* do the ai controlled players */
  48.     sniff_packets(); /* get player requests and handle them */
  49.     end_turn();      /* main turn update */
  50.     game_next_year();
  51.   }
  52.  
  53.  
  54. Most time is spend in the sniff_packets() function, where a select()
  55. call waits for packets or input on stdin(server-op commands).
  56.  
  57. ===========================================================================
  58. Server Autogame Testing
  59. ===========================================================================
  60. Code changes should always be tested before submission for inclusion
  61. into the svn source tree. It is useful to run the client and server as
  62. autogames to verify either a particular savegame no longer shows a
  63. fixed bug, or as a random sequence of games in a while loop overnight.
  64.  
  65. To start a server game with all AI players, create a file (below named
  66. civ.serv) with lines such as the following:
  67.  
  68. # set gameseed 42       # repeat a particular game (random) sequence
  69. # set mapseed 42        # repeat a particular map generation sequence
  70. # set timeout 3         # run a client/server autogame
  71. set timeout -1          # run a server only autogame
  72. set aifill 7            # fill to 7 players
  73. hard                    # make the AI do complex things
  74. create Caesar           # first player (with known name) created and 
  75.                         # toggled to AI mode
  76. start
  77.  
  78. Note: After the start command the server prompt is unusable in
  79. autogame mode.
  80.  
  81. The commandline to run server-only games can be typed as variations
  82. of:
  83. $ while( time server/civserver -r civ.serv ); do date; done
  84.   ---  or  ---
  85. $ server/civserver -r civ.serv -f buggy1534.sav.gz
  86.  
  87. To attach one or more clients to an autogame, remove the "start"
  88. command, start the server program and attach clients to created AI
  89. players. Or type "aitoggle <player>" at the server command prompt for
  90. each player that connects. Finally, type "start" when you are ready to
  91. watch the show.
  92.  
  93. Note, that the server will eventually flood a client with updates
  94. faster than they can be drawn to the screen, thus it should always be
  95. throttled by setting a timeout value high enough to allow processing
  96. of the large update loads near the end of the game. 
  97.  
  98. The autogame mode with timeout -1 is only available in DEBUG versions
  99. and should not be used with clients as it removes virtually all the
  100. server gating controls.
  101.  
  102. ===========================================================================
  103. Data Structures
  104. ===========================================================================
  105. For variable length list of fx units and cities freeciv uses a genlist,
  106. which is implemented in common/genlist.c. By some macro magic type specific
  107. macros have been defined, avoiding much trouble.
  108. For example a tile struct (the pointer to it we call ptile) has a unit
  109. list, ptile->units; to iterate though all the units on the tile you would
  110. do the following:
  111.  
  112. unit_list_iterate(ptile->units, punit) {
  113. /* In here we could do something with punit, which is a pointer to a
  114.     unit struct */
  115. } unit_list_iterate_end;
  116.  
  117. Note that the macro itself declares the variable punit.
  118. Similarly there is a 
  119.  
  120. city_list_iterate(pplayer->cities, pcity) {
  121. /* Do something with pcity, the pointer to a city struct */
  122. } city_list_iterate_end;
  123.  
  124. There are other operations than iterating that can be performed on a list;
  125. inserting, deleting, sorting etc. See common/speclist.h
  126. Note that the way the *_list_iterate macro is implemented means you can use
  127. "continue" and "break" in the usual manner.
  128.  
  129. One thing you should keep in the back of your mind: Say you are iterating
  130. through a unit list, and then somewhere inside the iteration decide to
  131. disband a unit. In the server you would do this by calling
  132. wipe_unit(punit), which would then remove the unit node from all the
  133. relevant unit lists. But by the way unit_list_iterate works, if the removed
  134. unit was the following node unit_list_iterate will already have saved the
  135. pointer, and use it in a moment, with a segfault as the result. To avoid 
  136. this, use unit_list_iterate_safe instead.
  137.  
  138. You can also define your own lists with operations like iterating; read how
  139. in common/speclist.h.
  140.  
  141. =========================================================================
  142. Network and Packets
  143. =========================================================================
  144. The basic netcode is located in server/sernet.c and client/clinet.c.
  145.  
  146. All information passed between the server and clients, must be sent
  147. through the network as serialized packet structures.
  148. These are defined in common/packets.h.
  149.  
  150. For each 'foo' packet structure, there is one send and one receive function:
  151.  
  152. int            send_packet_foo    (struct connection *pc,
  153.                      struct packet_foo *packet);
  154. struct packet_foo * receive_packet_foo    (struct connection *pc);
  155.  
  156. The send_packet_foo() function serializes a structure into a bytestream
  157. and adds this to the send buffer in the connection struct.
  158. The receive_packet_foo() function de-serializes a bytestream into a
  159. structure and removes the bytestream from the input buffer in the
  160. connection struct.
  161. The connection struct is defined in common/connection.h.
  162.  
  163. Each structure field in a structure is serialized using architecture
  164. independent functions such as dio_put_uint32() and de-serialized with
  165. functions like dio_get_uint32().
  166.  
  167. A packet is constituted by header followed by the serialized structure
  168. data. The header contains the following fields:
  169.  
  170. uint16    :    length        (the length of the entire packet)
  171. uint8    :    type        (e.g. PACKET_TILE_INFO)
  172.  
  173. To demonstrate the route for a packet through the system, here's how
  174. a unit disband is performed:
  175.  
  176. 1)  A player disbands a unit.
  177. 2)  The client initializes a packet_unit_request structure, and calls the
  178.     packet layer function send_packet_unit_request() with this structure and
  179.     packet type: PACKET_UNIT_DISBAND.
  180. 3)  The packet layer serializes the structure, wraps it up in a packet
  181.     containing the packetlength, type and the serialized data. Finally 
  182.     the data is send to the server.
  183. 4)  On the server the packet is read. Based on the type, the corresponding
  184.     de-serialize function is called is called by get_packet_from_connection(). 
  185. 5)  A packet_unit_request is initialized with the bytestream.
  186. 6)  Since the incoming packet is a request (a request in this context 
  187.     is every packet sent from the client to the server) the server sends a 
  188.     PACKET_PROCESSING_STARTED packet to the client.
  189. 7)  Finally the corresponding packet-handler, handle_unit_disband() function,
  190.     is called with the newly constructed structure.
  191. 8)  The handler function checks if the disband request is legal (is the sender
  192.     really the owner of the unit) etc.
  193. 9)  The unit is disbanded => wipe_unit() => send_remove_unit().
  194. 10) Now an integer, containing the id of the disbanded unit is
  195.     wrapped into a packet along with the type PACKET_REMOVE_UNIT:
  196.     send_packet_generic_integer().
  197. 11) The packet is serialized and send across the network.
  198. 12) The packet-handler returns and the end of the processing is 
  199.     announced to the client with a PACKET_PROCESSING_FINISHED packet.
  200. 13) On the client the PACKET_REMOVE_UNIT packet is deserialized into 
  201.     a packet_generic_integer structure.
  202. 14) The corresponding client handler function is now called 
  203.     handle_remove_unit(), and finally the unit is disbanded.
  204.  
  205. Notice that the two packets (PACKET_UNIT_DISBAND and
  206. PACKET_REMOVE_UNIT) were generic packets.  That means the packet
  207. structures involved, are used by various requests.  The
  208. packet_unit_request() is for example also used for the packets
  209. PACKET_UNIT_BUILD_CITY and PACKET_UNIT_CHANGE_HOMECITY.
  210.  
  211. When adding a new packet type, check to see if you can reuse some of the
  212. existing packet types. This saves you the trouble of
  213. writing new serialize/deserialize functions.
  214.  
  215. The PACKET_PROCESSING_STARTED and PACKET_PROCESSING_FINISHED packets
  216. from above serve two main purposes:
  217.  
  218.  - they allow the client to identify what causes a certain packet the
  219.  client receives. If the packet is framed by PACKET_PROCESSING_STARTED
  220.  and PACKET_PROCESSING_FINISHED packets it is the causes of the
  221.  request. If not the received packet was not caused by this client
  222.  (server operator, other clients, server at a new turn)
  223.  
  224.  - after a PACKET_PROCESSING_FINISHED packet the client can test if
  225.  the requested action was performed by the server. If the server has
  226.  sent some updates the client data structure will now hold other
  227.  values.
  228.  
  229. The PACKET_FREEZE_HINT and PACKET_THAW_HINT packets serve two
  230. purposes:
  231.  
  232.  - Packets send between these two packets may contain multiple
  233.  information packets which may cause multiple updates of some GUI
  234.  items. PACKET_FREEZE_HINT and PACKET_THAW_HINT can now be used to
  235.  freeze the GUI at the time PACKET_FREEZE_HINT is received and only
  236.  update the GUI after the PACKET_THAW_HINT packet is received.
  237.  
  238.  - Packets send between these two packets may contain contradicting
  239.  information which may confuse a client-side AI (agents for
  240.  example). So any updates send between these two packets are only
  241.  processed after the PACKET_THAW_HINT packet is received.
  242.  
  243. The following areas are wrapped by PACKET_FREEZE_HINT and
  244. PACKET_THAW_HINT:
  245.  
  246.  - the data send if a new game starts
  247.  - the data send to a reconnecting player
  248.  - the end turn activities
  249.  
  250. The Xaw client uses XtAppAddInput() to tell Xt to call the callback
  251. functions, when something happens on the client socket.
  252. The GTK+ client uses a similar gdk_input_add() call.
  253.  
  254. =========================================================================
  255. Network Improvements
  256. =========================================================================
  257.  
  258. In previous versions when a connection send buffer in the server got full
  259. we emptied the buffer contents and continued processing. Unfortunately this
  260. caused incomplete packets to be sent to the client, which caused crashes
  261. in either the client or the server, since the client cannot detect this
  262. situation. This has been fixed by closing the client connection when the
  263. buffer is emptied.
  264.  
  265. We also had (and still have) several problems related to flow control.
  266. Basically the problem is the server can send packets much faster than the
  267. client can process them. This is especially true when in the end of the
  268. turn the AIs move all their units. Unit moves in particular take a long
  269. time for the client to process since by default smooth unit moves is on.
  270.  
  271. There are 3 ways to solve this problem:
  272. 1) We wait for the send buffers to drain before continuing processing.
  273. 2) We cut the player's connection and empty the send buffer.
  274. 3) We lose packets (this is similar to 2) but can cause an incoherent
  275.    state in the client).
  276.  
  277. We mitigated the problem by increasing the send buffer size on the server
  278. and making it dynamic. We also added in strategic places in the code calls
  279. to a new flush_packets() function that makes the server stall for some time
  280. draining the send buffers. Strategic places include whenever we send the
  281. whole map. The maximum amount of time spent per flush_packets() call is
  282. specified by the 'netwait' variable.
  283.  
  284. To disconnect unreachable clients we added two other features: the server
  285. terminates a client connection if it doesn't accept writes for a period
  286. of time (set using the 'tcptimeout' variable). It also pings the client
  287. after a certain time elapses (set using the 'pingtimeout' variable). If
  288. the client doesn't reply its connection is closed.
  289.  
  290. =========================================================================
  291. Graphics
  292. =========================================================================
  293. Currently the graphics is stored in the PNG file format (other formats
  294. may be readable by some clients).
  295.  
  296. If you alter the graphics, then make sure that the background remains
  297. transparent.  Failing to do this means the mask-pixmaps will not be
  298. generated properly, which will certainly not give any good results.
  299.  
  300. Each terrain tile is drawn in 16 versions, all the combinations with
  301. with a green border in one of the main directions. Hills, mountains,
  302. forests and rivers are treated in special cases.
  303.  
  304. The Xaw client requires that the graphics be stored in "paletted" PNGs,
  305. which for graphics with few colors is probably a good idea anyway. It also
  306. has a limited number of colors available, although it will try to match
  307. similar-looking colors after the existing supply has been exhausted.  Of
  308. course, not every tileset has to be usable by the Xaw client.
  309.  
  310. Isometric tilesets are drawn in a similar way to how civ2 draws (that's
  311. why civ2 graphics are compatible).  For each base terrain type there
  312. exists one tile sprite for that terrain.  The tile is blended with
  313. nearby tiles to get a nice-looking boundary.  This is erronously called
  314. "dither" in the code.
  315.  
  316. Non-isometric tilesets draw the tiles in the "original" freeciv way,
  317. which is both harder and less pretty.  There are multiple copies of
  318. each tile, so that a different copy can be drawn depending the terrain
  319. type of the adjacent tiles.  It may eventually be worthwhile to convert
  320. this to the civ2 system.
  321.  
  322. =========================================================================
  323. Diplomacy
  324. =========================================================================
  325. A few words about the diplomacy system. When a diplomacy meeting is
  326. established, a Treaty structure is created on both of the clients and
  327. on the server. All these structures are updated concurrently as clauses
  328. are added and removed.
  329.  
  330. =========================================================================
  331. Map structure
  332. =========================================================================
  333. The map is maintained in a pretty straightforward C array, containing
  334. X*Y tiles. You can use the function
  335. struct tile *map_get_tile(x, y)
  336. to find a pointer to a specific tile.
  337. A tile has various fields; see the struct in common/map.h
  338.  
  339. When operating on tiles you normally iterate over x and y and maybe use
  340. map_get_tile() to get the tile struct.
  341. When fx iterating in a square around a map position (x,y) the naive method
  342.  
  343. for (x1 = x-1; x1 <= x+1; x1++)
  344.   for (y1 = y-1; y1 <= y+1; y1++)
  345.     /* do something */
  346.  
  347. would sometimes, fx if (x,y) = (0,0) , give tiles like (-1,0) or (0,-1)
  348. Because the map wraps in the x direction the first position should be
  349. [assuming the map has the size (map.xsize,map.ysize)] (map.xsize-1, 0), while
  350. the second tile (0,-1) is not a real time at all!
  351. This could be solved by the following:
  352.  
  353. for (x1 = x-1; x1 <= x+1; x1++) {
  354.   for (y1 = y-1; y1 <= y+1; y1++) {
  355.     int abs_x = x1, abs_y = y1;
  356.     if (!normalize_map_pos(&abs_x, &abs_y))
  357.       continue;
  358.     /* do something with abs_x, abs_y */
  359.   }
  360. }
  361.  
  362. normalize_map_pos() will adjust the values of abs_x, abs_y to fix within
  363. the map, and if the original pos does not correspond to a tile, as (0, -1),
  364. it will return 0.
  365. Alternatively this could have all been done via the macro call
  366.  
  367. square_iterate(x, y, 1/*radius*/, x1, y1)  {
  368. /* do something */
  369. } square_iterate_end;
  370.  
  371. which automatically adjust the tile values. The defined macros should be
  372. used whenever possible, the example of a "manual" square iterate was only
  373. included to give people the knowledge of how things work.
  374.  
  375. Also available is the function real_map_distance(), which takes wrap and
  376. such things into account. It does not however take terrain and roads, etc.
  377. into account. For that you would use a move_cost_map, which is generated
  378. via the function generate_warmap(), and calculates the distances from a
  379. tile to all other tiles on the map. See server/gotohand.c.
  380.  
  381. Note that if all the code that operate on x and y values used macros, it
  382. would be very simple to convert these, to allow fx a flat world or a map
  383. structure like in civ2 for isometric view.
  384.  
  385. Almost all functions expect that any passed map positions are normal
  386. (is_normal_map_pos returns true). Currently there is no known
  387. exception of this rule. To assert this the CHECK_MAP_POS macro should
  388. be used.
  389.  
  390. =========================================================================
  391. Different types of map topology
  392. =========================================================================
  393.  
  394. Originally Freeciv supports only a simple rectangular map.  For instance
  395. a 5x3 map would be conceptualized as
  396.  
  397.   <- XXXXX ->
  398.   <- XXXXX ->
  399.   <- XXXXX ->
  400.  
  401. and it looks just like that under "overhead" (non-isometric) view (the
  402. arrows represent an east-west wrapping).  But under an isometric-view
  403. client, the same map will look like
  404.  
  405.      X
  406.     X X
  407.    X X X
  408.     X X X
  409.      X X X
  410.       X X
  411.        x
  412.  
  413. where "north" is to the upper-right and "south" to the lower-left.  This
  414. makes for a mediocre interface.
  415.  
  416. An isometric-view client will behave better with an isometric map.  This is
  417. what Civ2, SMAC, Civ3, etc. all use.  A rectangular isometric map can be
  418. conceptualized as
  419.  
  420.   <- X X X X X  ->
  421.   <-  X X X X X ->
  422.   <- X X X X X  ->
  423.   <-  X X X X X ->
  424.  
  425. (north is up) and it will look just like that under an isometric-view client.
  426. Of course under an overhead-view client it will again turn out badly.
  427.  
  428. Both types of maps can easily wrap in either direction: north-south or
  429. east-west.  Thus there are four types of wrapping: flat-earth, vertical
  430. cylinder, horizontal cylinder, and torus.  Traditionally Freeciv only wraps
  431. in the east-west direction.
  432.  
  433. =========================================================================
  434. Different coordinate systems
  435. =========================================================================
  436.  
  437. In Freeciv, we have the general concept of a "position" or "tile".  A tile
  438. can be referred to in any of several coordinate systems.  The distinction
  439. becomes important when we start to use non-standard maps (see above).
  440.  
  441.   Here is a diagram of coordinate conversions for a classical map.
  442.  
  443.       map        natural      native
  444.  
  445.       ABCD        ABCD         ABCD
  446.       EFGH  <=>   EFGH     <=> EFGH   <=> ABCDEFGHIJKL
  447.       IJKL        IJKL         IJKL
  448.  
  449.   Here is a diagram of coordinate conversions for an iso-map.
  450.  
  451.      map          natural     native       index
  452.  
  453.         CF        A B C         ABC     
  454.        BEIL  <=>   D E F   <=>  DEF   <=> ABCDEFGHIJKL
  455.       ADHK        G H I         GJI
  456.        GJ          J K L        JKL
  457.  
  458. Below each of the coordinate systems are explained in more detail.
  459.  
  460. - Map (or "standard") coordinates.
  461.  
  462.   All of the code examples above are in map coordinates.  These preserve
  463.   the local geometry of square tiles, but do not represent the global map
  464.   geometry well.  In map coordinates, you are guaranteed (so long as we use
  465.   square tiles) that the tile adjacency rules
  466.  
  467.       (map_x-1, map_y-1)    (map_x, map_y-1)   (map_x+1, map_y-1)
  468.       (map_x-1, map_y)      (map_x, map_y)     (map_x+1, map_y)
  469.       (map_x-1, map_y+1)    (map_x, map_y+1)   (map_x+1, map_y+1)
  470.  
  471.   are preserved, regardless of what the underlying map or drawing code
  472.   looks like.  This is the definition of the system.
  473.  
  474.   Map coordinates are easiest for local operations (like square_iterate
  475.   or adjc_iterate) but unwieldy for global operations.
  476.  
  477. - Natural coordinates.
  478.  
  479.   Natural coordinates preserve the geometry of map coordinates, but also have
  480.   the rectangular property of native coordinates.  They are unwieldy for
  481.   most operations because of their sparseness - they may not have the same
  482.   scale as map coordinates and, in the iso case, there are gaps in the
  483.   natural representation of a map.
  484.  
  485. - Native coordinates.
  486.  
  487.   With an iso-rectangular map, global operations are difficult using map
  488.   coordinates.  Imagine a simple iso-rectangular map.  Its "natural"
  489.   representation is
  490.  
  491.                  A B C        (0,0)   (2,0)   (4,0)
  492.                   D E F  <=>      (1,1)   (3,1)   (5,1)
  493.                  G H I        (0,2)   (2,2)   (4,2)
  494.  
  495.   while its representation in map coordinates would be
  496.  
  497.                      CF                   (2,0) (3,0)
  498.                     BEI  <=>        (1,1) (2,1) (3,1)
  499.                    ADH        (0,2) (1,2) (2,2)
  500.                     G               (1,3)
  501.  
  502.   Neither is particularly good for a global map operation such as
  503.   whole_map_iterate.  Something better is needed.
  504.  
  505.   Native coordinates compress the map into a continuous rectangle; the
  506.   dimensions are defined as map.xsize x map.ysize.  For instance the
  507.   above iso-rectangular map is represented in native coordinates by
  508.   compressing the natural representation in the X axis to get the
  509.   3x3 iso-rectangle of
  510.  
  511.                     ABC       (0,0) (1,0) (2,0)
  512.                     DEF  <=>  (0,1) (1,1) (2,1)
  513.                     GHI       (0,2) (1,2) (3,2)
  514.  
  515.   The resulting coordinate system is much easier to use than map
  516.   coordinates for some operations.  These include most internal topology
  517.   operations (e.g., normalize_map_pos, whole_map_iterate) as well as
  518.   storage (in map.tiles and savegames, for instance).
  519.  
  520.   In general, native coordinates can be defined based on this property:
  521.   the basic map becomes a continuous (gap-free) cardinally-oriented
  522.   rectangle when expressed in native coordinates.
  523.  
  524. - Index coordinates.
  525.  
  526.   Index coordinates simply reorder the map into a continous (filled-in)
  527.   one-dimensional system.  This coordinate system is closely tied to
  528.   the ordering of the tiles in native coordinates, and is slightly
  529.   easier to use for some operations (like storage) because it is
  530.   one-dimensional.  In general you can't assume anything about the ordering
  531.   of the positions within the system.
  532.  
  533. With a classical rectangular map, the first three coordinate systems are
  534. equivalent.  When we introduce isometric maps, the distinction becomes
  535. important, as demonstrated above.  Many places in the code have
  536. introduced "map_x/map_y" or "nat_x/nat_y" to help distinguish whether
  537. map or native coordinates are being used.  Other places are not yet
  538. rigorous in keeping them apart, and will often just name their variables
  539. "x" and "y".  The latter can usually be assumed to be map coordinates.
  540.  
  541. Note that map.xsize and map.ysize define the dimension of the map in
  542. _native_ coordinates.
  543.  
  544. Of course, if a future topology does not fit these rules for coordinate
  545. systems, they will have to be refined.
  546.  
  547. =========================================================================
  548. Native coordinates on an isometric map
  549. =========================================================================
  550.  
  551. An isometric map is defined by the operation that converts between map
  552. (user) coordinates and native (internal) ones.  In native coordinates, an
  553. isometric map behaves exactly the same way as a standard one.  (See
  554. "native coordinates", above.
  555.  
  556. Converting from map to native coordinates involves a pi/2 rotation (which
  557. scales in each dimension by sqrt(2)) followed by a compression in the X
  558. direction by a factor of 2.  Then a translation is required since the
  559. "normal set" of native coordinates is defined as
  560.   {(x, y) | x: [0..map.xsize) and y: [0..map.ysize)}
  561. while the normal set of map coordinates must satisfy x >= 0 and y >= 0.
  562.  
  563. Converting from native to map coordinates (a less cumbersome operation) is
  564. the opposite.
  565.                                         EJ
  566.            ABCDE     A B C D E         DIO
  567.   (native) FGHIJ <=>  F G H I J <=>   CHN  (map)
  568.            KLMNO     K L M N O       BGM
  569.                                     AFL
  570.                                      K
  571.  
  572. Note that
  573.  
  574.   native_to_map_pos(0, 0) == (0, map.xsize-1)
  575.   native_to_map_pos(map.xsize-1, 0) == (map.xsize-1, 0)
  576.   native_to_map_pos(x, y+2) = native_to_map_pos(x,y) + (1,1)
  577.   native_to_map_pos(x+1, y) = native_to_map_pos(x,y) + (1,-1)
  578.  
  579. The math then works out to
  580.  
  581.   map_x = ceiling(nat_y / 2) + nat_x
  582.   map_y = floor(nat_y / 2) - nat_x + map.xsize - 1
  583.  
  584.   nat_y = map_x + map_y - map.xsize
  585.   nat_x = floor(map_x - map_y + map.xsize / 2)
  586.  
  587. which leads to the macros native_to_map_pos, map_to_native_pos,
  588. map_pos_to_native_x, and map_pos_to_native_y that are defined in map.h.
  589.  
  590. =========================================================================
  591. Unknown tiles and Fog of War
  592. =========================================================================
  593.  
  594. In the tile struct there is a field
  595.  
  596. struct tile {
  597.   ...
  598.   unsigned int known;
  599.   ...
  600. };
  601.  
  602. On the server the known fields is considered to be a bitvector, one
  603. bit for each player, 0==tile unknown, 1==tile known.
  604. On the client this field contains one of the following 3 values:
  605.  
  606. enum known_type {
  607.  TILE_UNKNOWN, TILE_KNOWN_FOGGED, TILE_KNOWN
  608. };
  609.  
  610. The values TILE_UNKNOWN, TILE_KNOWN are straightforward. TILE_FOGGED
  611. is a tile of which the user knows the terrain (inclusive cities, roads,
  612. etc...).
  613.  
  614. TILE_UNKNOWN tiles are (or should be) never sent to the client.  In the past
  615. UNKNOWN tiles that were adjacent to FOGGED or KNOWN ones were sent to make
  616. the drawing process easier, but this has now been removed.  This means
  617. exploring new land may sometimes change the appearance of existing land (but
  618. this is not fundamentally different from what might happen when you
  619. transform land).  Sending the extra info, however, not only confused the
  620. goto code but allowed cheating.
  621.  
  622. Fog of war is the fact that even when you have seen a tile once you are
  623. not sent updates unless it is inside the sight range of one of your units
  624. or cities.
  625. We keep track of fog of war by counting the number of units and cities
  626. [and nifty future things like radar outposts] of each client that can
  627. see the tile. This requires a number per player, per tile, so each tile
  628. has a short[]. Every time a unit/city/miscellaneous can observe a tile
  629. 1 is added to its player's number at the tile, and when it can't observe
  630. any more (killed/moved/pillaged) 1 is subtracted. In addition to the
  631. initialization/loading of a game this array is manipulated with the
  632. void unfog_area(struct player *pplayer, int x, int y, int len)
  633. and
  634. void fog_area(struct player *pplayer, int x, int y, int len)
  635. functions. "int len" is the radius of the area that should be
  636. fogged/unfogged, i.e. a len of 1 is a normal unit. In addition to keeping
  637. track of fog of war, these functions also make sure to reveal TILE_UNKNOWN
  638. tiles you get near, and send info about TILE_UNKNOWN tiles near that the
  639. client needs for drawing. They then send the tiles to
  640. void send_tile_info(struct player *dest, int x, int y)
  641. which then sets the correct known_type and sends the tile to the client.
  642.  
  643. If you want to just show the terrain and cities of the square the
  644. function show_area does this. The tiles remain fogged.
  645. If you play without fog of war all the values of the seen arrays are
  646. initialized to 1. So you are using the exact same code, you just never
  647. get down to 0. As changes in the "fogginess" of the tiles are only sent
  648. to the client when the value shifts between zero and non-zero, no
  649. redundant packages are sent. You can even switch fog of war on/off
  650. in game just by adding/subtracting 1 to all the tiles.
  651.  
  652. We only send city and terrain updates to the players who can see the
  653. tile. So a city (or improvement) can exist in a square that is known and
  654. fogged and not be shown on the map. Likewise, you can see a city in a
  655. fogged square even if the city doesn't exist (it will be removed when
  656. you see the tile again). This is done by 1) only sending info to players
  657. who can see a tile 2) keeping track of what info has been sent so the
  658. game can be saved. For the purpose of 2) each player has a map on the
  659. server (consisting of player_tile's and dumb_city's) where the relevant
  660. information is kept.
  661.  
  662. The case where a player p1 gives map info to another player p2: This
  663. requires some extra info. Imagine a tile that neither player sees, but
  664. which p1 have the most recent info on. In that case the age of the players'
  665. info should be compared which is why the player tile has a last_updated
  666. field.
  667. This field is not kept up to date as long as the player can see the tile
  668. and it is unfogged, but when the tile gets fogged the date is updated.
  669.  
  670. [An alternative solution would be to give each tile a list
  671. of the units and cities that observe it. IMO this would not be any
  672. easier than just counting, and would have no benefits. The current
  673. solution also gives the possibility to reveal squares as you like,
  674. say near a radar tower tile special. Very flexible.]
  675.  
  676. [The barbarians and the ai take their map info directly from the server,
  677. so they can currently ignore fog of war, and they do so. I really think
  678. that the ideal AI wouldn't be cheating like this.]
  679.  
  680. There is now a shared vision feature, meaning that if p1 gives shared
  681. vision to p2, every time a function like show_area, fog_area, unfog_area
  682. or give_tile_info_from_player_to_player is called on p1 p2 also gets the
  683. info. Note that if p2 gives shared info to p3, p3 also gets the info.
  684. This is controlled by p1's really_gives_vision bitvector, where the
  685. dependencies will be kept.
  686.  
  687. If there is anything I have explained inadequately in this section you
  688. can ask me on <thue@diku.dk>.
  689. -Thue
  690.  
  691. =========================================================================
  692. National borders
  693. =========================================================================
  694. For the display of national borders (similar to those used in Sid Meier's
  695. Alpha Centauri) each map tile also has an "owner" field, to identify
  696. which nation lays claim to it. If game.borders is non-zero, each city
  697. claims a circle of tiles game.borders in radius (in the case of neighbouring
  698. enemy cities, tiles are divided equally, with the older city winning any
  699. ties). Cities claim all immediately adjacent tiles, plus any other tiles
  700. within the border radius on the same continent. Land cities also claim ocean
  701. tiles if they are surrounded by 5 land tiles on the same continent (this is
  702. a crude detection of inland seas or lakes, which should be improved upon).
  703.  
  704. Tile ownership is decided only by the server, and sent to the clients, which
  705. draw border lines between tiles of differing ownership. Owner information is
  706. sent for all tiles that are known by a client, whether or not they are fogged.
  707. A patch to convert this to "semi-fogged" behaviour, whereby clients receive
  708. limited information about non-neighbouring and unseen enemies, is available
  709. at http://freecivac.sf.net/.
  710.  
  711. =========================================================================
  712. Client GUI- Athena 
  713. =========================================================================
  714. One client GUI is written using athena-widgets. A few comments on this 
  715. could prove useful for anyone wishing to write new dialogs or improve
  716. on the current ones.
  717.  
  718. Widgets:
  719. --------
  720. When you create new widgets for a dialog, like:
  721.  
  722.   players_form = XtVaCreateManagedWidget("playersform", 
  723.                        formWidgetClass, 
  724.                        players_dialog_shell, NULL);
  725.  
  726. then put the widget properties in the app-default file 'Freeciv', instead
  727. of hardcoding them. For the widget created above, the following entries
  728. in the app-default file applies:
  729.  
  730. *playersform.background:          lightblue
  731. *playersform.resizable:           true
  732. *playersform.top:                 chainTop
  733. *playersform.bottom:              chainBottom
  734. *playersform.left:                chainLeft
  735. *playersform.right:               chainRight
  736.  
  737. Pixcomm and Canvas:
  738. -------------------
  739. The Pixcomm is a subclassed Command-widget, which can displays a Pixmap
  740. instead of a string, on top of a button(command). The Pixcomm widget
  741. should be used all places where this kind of high-level functionality
  742. is required. 
  743.  
  744. The Canvas widget is more low-level. One have to write an expose(redraw)
  745. event-handler for each widget. The widget generates events on resize
  746. and mousebuttons.
  747.  
  748. [Reading any Xt documentation, will tell you how powerful widget
  749. subclassing is. So I went trough great troubles subclassing the
  750. command widget. It was not before long I got mails from unhappy Xaw3d
  751. (and derives) users, that the client keeps crashing on them. Turns
  752. out that subclassing from any widgets but Core, chains the new
  753. widgets to libXaw. In hindsight I should just subclassed the Canvas
  754. widget and add more highlevel functionality. -PU]
  755.  
  756. ===========================================================================
  757. Misc - The idea trashcan 
  758. ===========================================================================
  759. [Currently all of the major entities - units, cities, players, contains
  760. an unique id. This id is really only required when a reference to an entity
  761. is to be serialized(saved or distributed over the net). However in the
  762. current code, the id is also used for comparing, looking up and in general
  763. referencing entities. This results in a lot of mess and unnecessary duplicate
  764. functions. Often when programming, one wonders if some function needs
  765. the id or a pointer when referring to an entity. -PU]
  766.  
  767. The paragraph above isn't true anymore for player, units and cities. -RF
  768.  
  769. ===========================================================================
  770.  
  771. Player-related entities in Freeciv - by Reinier Post <reinpost@win.tue.nl>
  772. + by dwp@mso.anu.edu.au
  773.  
  774. Freeciv is confused about the meaning of 'player'.  As a participant in
  775. Freeciv games, you'll notice that the participants are called 'players'.
  776. At the same time, players seem to be identified with civilizations.
  777. On the other hand, civilizations seem to be identified by 'nation':
  778. every player chooses a nation at the start of the game.
  779.  
  780. In the data structures, a 'player' identifies a civilization, not a user.
  781.  
  782. ----
  783.   THE PLAN:
  784.  
  785. There are four player-related entities:
  786.  
  787. + player
  788.   A civilization, with a capital, cities, units, an income, etc.
  789.  
  790. + nation
  791.   A type of civilization (except that very little actually depends on
  792.   nation, and the oddity exists that each player must be of different 
  793.   nation)
  794.  
  795. + user
  796.   Identifies 'someone out there', usually a human user running a civclient
  797.   (this is the plan; it is not yet implemented).
  798.  
  799. + connection
  800.   Records a client connection; like a user, but disappears when the user 
  801.   disconnects, whereas for real users we may want to remember them between 
  802.   connections.  See Connections section below.
  803.  
  804. Where do these entities exist?
  805.  
  806. Nations aren't actually used for annything that matters; for them,
  807. so the question isn't very interesting.
  808.  
  809. Players (more aptly named, 'civilizations'), exist in games.  Except in
  810. the context of a running game, the entity makes no sense.  Players and
  811. their status are part of savefiles.  A game can be saved and restarted
  812. on a different server; the players will be the same.  A new game will
  813. have new players.  Players exist in common/ (even games do) but a
  814. client only has one instantiated player.
  815.  
  816. The reason to introduce users is client-side server commands.  It must
  817. be possible to assign different levels of access to commands to different
  818. users.  Attaching it to players is not good enough: the information must
  819. survive the addition and removal of other players, the start or restart
  820. of a game, reconnections by the same user even from different computers,
  821. or transferral of the game to a different server.  However, a user
  822. may have different levels of access in different games.
  823.  
  824. While they last, connections are sufficient identification for users.
  825. The user entity will allow users to be identified when they reconnect.
  826.  
  827. Ideally, users would be identified with unique global ids, handed out
  828. by a 'registry service' similar to the metaserver, but this would be
  829. too cumbersome in practice.  So the plan is to make users persist in
  830. a server session (even whan a game is started, or restarted when that
  831. option is added) and make them persist across games (when a saved
  832. game is loaded in a different server session).
  833.  
  834. Users will be created when they first connect to a server, remembered by
  835. the running server and in savefiles.  Upon connecting, the client will
  836. be sent a unique session id, generated when the server started, plus a
  837. fresh user id; it will store them in a ~/.civcookie file, and send it
  838. back when trying to reconnect.  This will allow the identity of users
  839. to be protected.  'Protected' players will only allow the same user to
  840. reconnect; 'unprotected' ones allow anyone to connect; server commands
  841. and probably client options will be available to control this.
  842.  
  843. Player names will be assigned to users, not players.
  844.  
  845. The server maintains a default access level, which is used for new
  846. users and unprotected ones.
  847.  
  848. ----
  849.   THE PRESENT IMPLEMENTATION:
  850.  
  851. Currently access levels are stored in the connection struct.  This allows 
  852. access levels to be assigned to each individual connected player, which 
  853. would not be the case if they were directly assigned to the player struct 
  854. (due to the fact that the players array changes when players are added or 
  855. removed).
  856.  
  857. But that's it.
  858.  
  859. Players are still created before the game is started, and player names
  860. still belong to players.  Access levels exist in client and server, 
  861. but only the server uses them.  User ids are not yet implemented;
  862. Server ids do not exist at all.
  863.  
  864. Commands to protect/unprotect users do not yet exist; they would serve 
  865. no useful purpose.
  866.  
  867. Access levels can set for individual users, including AI players with 
  868. a connected observer, but only while someone is connected; they will not 
  869. be remembered when the user disconnects.
  870.  
  871. ===========================================================================
  872. Connections
  873. ===========================================================================
  874.  
  875. The code is currently transitioning from 1 or 0 connections per player
  876. only, to allowing multiple connections for each player (recall
  877. 'player' means a civilization, see above), where each connection may
  878. be either an "observer" or "controller".
  879.  
  880. This discussion is mostly about connection in the server.  The client
  881. only has one real connection: 'aconnection' - its connection to the
  882. server, though it does use some other connection structs (currently
  883. pplayer->conn) to store information about other connected clients
  884. (eg, capability strings).
  885.  
  886. In the old paradigm, server code would usually send information to a
  887. single player, or to all connected players (usually represented by
  888. destination being a NULL player pointer).  With multiple connections
  889. per player things become more complicated.  Sometimes information
  890. should be sent to a single connection, or to all connections for a
  891. single player, or to all (established) connections, etc.  To handle
  892. this, "destinations" should now be specified as a pointer to a struct
  893. conn_list (list of connections).  For convenience the following
  894. commonly applicable lists are maintained:
  895.    game.all_connections   -  all connections
  896.    game.est_connections   -  established connections
  897.    game.game_connections  -  connections observing and/or involved in game
  898.    pplayer->connections   -  connections for specific player
  899.    pconn->self            -  single connection (as list)
  900.  
  901. Connections can be classified as follows:  (first match applies)
  902.  
  903. 1. (pconn->used == 0) Not a real connection (closed/unused), should
  904.    not exist in any list of have any information sent to it.
  905.  
  906. (All following cases exist in game.all_connections.)
  907.  
  908. 2. (pconn->established == 0) TCP connection has been made, but initial
  909.    Freeciv packets have not yet been negotiated (join_game etc).
  910.    Exists in game.all_connections only.  Should not be sent any
  911.    information except directly as result of join_game etc packets, 
  912.    or server shutdown, or connection close, etc.
  913.  
  914. (All following cases exist in game.est_connections.)
  915.  
  916. 3. (pconn->player == NULL) Connection has been established, but is not
  917.    yet associated with a player.  Currently this is not possible, but
  918.    the plan is to allow this in future, so clients can connect and
  919.    then see list of players to choose from, or just control the server
  920.    or observe etc. Two subcases:
  921.  
  922.    3a. (pconn->observer == 0) Not observing the game.  Should receive
  923.        information about other clients, game status etc, but not map,
  924.        units, cities, etc.
  925.  
  926. (All following cases exist in game.game_connections.)
  927.  
  928.    3b. (pconn->observer == 1) Observing the game.  Exists in
  929.        game.game_connections.  Should receive game information about
  930.        map, units, cities, etc.
  931.  
  932. 4. (pconn->player != NULL) Connected to specific player, either as
  933.    "observer" or "controller".  (But observers not yet implemented.)
  934.    Exists in game.game_connections, and in pconn->player->connections.
  935.  
  936.  
  937. ===========================================================================
  938. Starting a Server from Within a Client
  939. ===========================================================================
  940.  
  941. After many years of complaints regarding the ease (or lack thereof) of
  942. starting a game of Freeciv [start a server, input settings on a command line,
  943. start a client, and connect, etc], a method has been developed for starting
  944. and playing a complete game using only the client. This has been called the
  945. "extended" or "new connect dialog". This is perhaps a misnomer, but there it 
  946. is. This win32 client has had this feature in some form for some time. 
  947.  
  948. It works by forking a server from within the client and then controlling that
  949. server via chatline messages. The guts of the machinery to do this can be
  950. found in these files:
  951.  
  952. client/connectdlg_common.[ch]
  953. client/gui-*/connectdlg.[ch]
  954. common/packets.def
  955. server/gamehand.[ch]
  956. server/stdinhand.[ch]
  957.  
  958. When a player starts a client, he is presents with several options: start
  959. a new game, continue a saved game and connect to a networked game. For the 
  960. latter option, connect_to_server() is called and login proceeeds as normal.
  961. The the first two options, connectdlg_common.c:client_start_server() is 
  962. called. Here, a server is spawned, standard input and outputs to that process
  963. are closed, and then connect_to_server() is called so the client connects to 
  964. that server.
  965.  
  966. At this point everything regarding the client/server connection is as usual;
  967. however, for the client to control the server, it must have access level HACK,
  968. so it must verify to the server that it is local (on the same machine or at
  969. least has access to the same disk as the server). The procedure is:
  970.  
  971. 1. the server creates a file using gamehand.c:create_challenge_filename() and
  972.    puts the name of this file in packet_server_join_reply that it sends back
  973.    to the client. The name of the file is semi-random.
  974. 2. The client, upon receiving confirmation that it can join the server,
  975.    creates a file using the name the server selected and places a random number
  976.    inside that file.
  977. 3. The client sends a packet [packet_single_want_hack_req] with that random 
  978.    number back to the server.
  979. 4. The server upon receiving the packet [packet_single_want_hack_req], opens
  980.    the file and compares the two numbers. If the file exists and the numbers
  981.    are equal the server grants that client HACK access level and sends a
  982.    packet [packet_single_want_hack_reply] informing the client of its elevated
  983.    access level.
  984.  
  985. Only one other packet is used --- packet_single_playerlist_req --- which asks
  986. the server to send a player list when a savegame is loaded. This list is used
  987. for player selection.
  988.  
  989.  
  990. ===========================================================================
  991. Macros and inline functions
  992. ===========================================================================
  993.  
  994. For a long time Freeciv had no inline functions, only macros.  With the
  995. use of other C99 features and some new requirements by the code, this has
  996. changed.  Now both macros and inline functions are used.
  997.  
  998. This causes problems because one coder may prefer to use a macro while
  999. another prefers an inline function.  Of course there was always some
  1000. discretion to the author about whether to use a function or a macro; all
  1001. we've done is add even more choices.
  1002.  
  1003. Therefore the following guidelines should be followed:
  1004.  
  1005. - Functions should only be put into header files when doing so makes a
  1006.   measurable impact on speed.  Functions should not be turned into macros or
  1007.   inlined unless there is a reason to do so.
  1008.  
  1009. - Macros that take function-like parameters should evaluate each parameter
  1010.   exactly once.  Any macro that doesn't follow this convention should be
  1011.   named in all upper-case letters as a MACRO.
  1012.  
  1013. - Iterator macros should respect "break".
  1014.  
  1015. - In header files macros are preferred to inline functions, but inline
  1016.   functions are better than MACROS.
  1017.  
  1018. - Functions or macros that are currently in one form do not have to be
  1019.   changed to the other form.
  1020.  
  1021. Note that many existing macros do not follow these guidelines.
  1022.  
  1023.  
  1024. ===========================================================================
  1025. Style Guide
  1026. ===========================================================================
  1027.  
  1028. See CodingStyle in this directory.
  1029.  
  1030. - If you send patches, use "diff -u" (or "diff -r -u").  For further
  1031.   information, see <http://www.freeciv.org/index.php/How_to_Contribute>.
  1032.   Also, name patch files descriptively (e.g. "fix-foo-bug-0.diff" is good,
  1033.   but "freeciv.diff" is not).
  1034.  
  1035. - When doing a "diff" for a patch, be sure to exclude unnecessary files
  1036.   by using the "-X" argument to "diff".  E.g.:
  1037.  
  1038.     % diff -ruN -Xdiff_ignore freeciv_svn freeciv >/tmp/fix-foo-bug-0.diff
  1039.  
  1040.   A suggested "diff_ignore" file is included in the Freeciv distribution.
  1041.  
  1042. ===========================================================================
  1043. Internationalization (I18N)
  1044. ===========================================================================
  1045.  
  1046. Messages and text in general which are shown in the GUI should be
  1047. translated by using the "_()" macro. In addition freelog(LOG_NORMAL,
  1048. ...) messages should be translated. The other loglevels (LOG_FATAL,
  1049. LOG_ERROR,LOG_VERBOSE, LOG_DEBUG) should NOT be translated.
  1050.  
  1051. (See utility/fciconv.[ch])
  1052. The data_encoding is used in all data files and network transactions.
  1053. This is UTF-8.  Currently, the rulesets are in latin1 (ISO-8859-1).
  1054.  
  1055. The internal_encoding is used internally within freeciv.  This is always
  1056. UTF-8 at the server, but can be configured by the GUI client.  (When your
  1057. charset is the same as your GUI library, GUI writing is easier.)
  1058.  
  1059. The local_encoding is the one supported on the command line.  This is not
  1060. under our control, and all output to the command line must be converted.
  1061.  
  1062. ===========================================================================
  1063.